package com.onlyxiahui.common.action.description.handler.impl.module;

import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.List;

import com.onlyxiahui.common.action.description.DocumentContext;
import com.onlyxiahui.common.action.description.bean.ModuleData;
import com.onlyxiahui.common.action.description.enums.annotation.MethodRequest;
import com.onlyxiahui.common.action.description.enums.annotation.ModuleMapping;
import com.onlyxiahui.common.action.description.handler.impl.BaseModuleHandler;
import com.onlyxiahui.common.action.description.util.ActionAnnotationUtil;

/**
 * Description <br>
 * Date 2020-01-07 15:28:56<br>
 * 
 * @author XiaHui [onlovexiahui@qq.com]<br>
 * @since 1.0.0
 */

public class ControllerModuleHandler extends BaseModuleHandler {

	@Override
	public boolean support(DocumentContext context, Class<?> classType) {
		Annotation[] as = classType.getAnnotations();

		boolean hasRequestMapping = ActionAnnotationUtil.hasAnnotation(ModuleMapping.RequestMapping.getAnnotation(), as);
		boolean hasRestController = ActionAnnotationUtil.hasAnnotation(ModuleMapping.RestController.getAnnotation(), as);
		boolean hasController = ActionAnnotationUtil.hasAnnotation(ModuleMapping.Controller.getAnnotation(), as);
		boolean hasActionMapping = ActionAnnotationUtil.hasAnnotation(ModuleMapping.ActionMapping.getAnnotation(), as);

		return (hasRequestMapping || hasRestController || hasController) && !hasActionMapping;
	}

	@Override
	public ModuleData handle(DocumentContext context, Class<?> classType) {
		Annotation[] cas = classType.getAnnotations();
		Object value = null;
		Object path = null;
		Annotation a = ActionAnnotationUtil.getAnnotation(MethodRequest.RequestMapping.getAnnotation(), cas);
		if (null == a) {
			a = ActionAnnotationUtil.getAnnotation(ModuleMapping.RestController.getAnnotation(), cas);
		}
		if (null != a) {
			value = ActionAnnotationUtil.getValue("value", a);
			path = ActionAnnotationUtil.getValue("path", a);
		}

		List<String> paths = new ArrayList<>();
		if (value instanceof String) {
			paths.add(value.toString());
		}
		if (value instanceof String[]) {
			String[] values = (String[]) value;
			if (null != values && values.length > 0) {
				for (String p : values) {
					paths.add(p);
				}
			}
		}

		if (path instanceof String) {
			paths.add(path.toString());
		}
		if (path instanceof String[]) {
			String[] values = (String[]) path;
			if (null != values && values.length > 0) {
				for (String p : values) {
					paths.add(p);
				}
			}
		}
		return binding(context, classType, paths);
	}
}
